package com.example.smartcity_poverty.ui

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_poverty.App
import com.example.smartcity_poverty.App.Companion.getTokenStr
import com.example.smartcity_poverty.App.Companion.url
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.databinding.FragmentNewsCommentBinding
import com.example.smartcity_poverty.databinding.FragmentNewsCommentEditBinding
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.network.AppApi
import com.example.smartcity_poverty.logic.network.ServiceNET.Companion.create
import com.example.smartcity_poverty.logic.util.Util.glide
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.logic.util.Util.startActivityUtils
import com.example.smartcity_poverty.ui.Home.HomeViewModel
import com.example.smartcity_poverty.ui.PersonalCenter.activity.LoginActivity
import kotlinx.android.synthetic.main.activity_show_news.*
import kotlinx.android.synthetic.main.fragment_news_comment.view.*
import kotlinx.android.synthetic.main.fragment_news_comment_edit.view.*
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 显示新闻文章详情
 */
@Suppress("DEPRECATION")
class ShowNewsActivity : AppCompatActivity() {


    private val TAG = this.javaClass.simpleName

    val id by lazy {
        intent.getStringExtra("id")?.toInt()
    }

    private val viewModel by lazy {
        ViewModelProviders.of(this)[HomeViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_show_news)
        title = "新闻文章详情"


        // 根据新闻ID来查找新闻详情
        news(id!!)

        // 加载新闻评论
        rvAdapter()

        onClickComment()
    }

    private fun onClickComment() {
        // 点击发表评论
        news_comment_include.news_edit_tvPOST.setOnClickListener {
            publishComment(id!!)
        }
    }

    /**
     * 根据Id进行显示新闻内容
     */
    private fun news(id: Int) = coroutine {

        // 发起网络请求获取新闻详情
        val rows = create<AppApi>().getNewsYes(id)
        if (rows.code == 200) {
            // 将数据填充到UI上
            runOnUiThread {
                glide(url + rows.data?.cover, showNewsImage)
                showNewsTitle.text = rows.data?.title
                showNewsTime.text = rows.data?.publishDate
                val content = App.addContentImgURL(rows.data?.content.toString(), url)
                showNewsContent.loadDataWithBaseURL(null, content, "text/html", " utf-8", null)
                showNewsLayout.visibility = View.VISIBLE
            }

        } else "加载新闻评论出错!".show()

    }


    /**
     * 配置列表适配器
     */
    private fun rvAdapter() {
        val data = ArrayList<NewsCommentModel>()
        coroutine(Dispatchers.Main) {
            // 获取新闻评论列表
            val result = api.getNewsCommentList(id!!)
            if (result.code == 200) {
                data.clear()
                for (i in result.rows) {
                    data.add(NewsCommentModel(i.userName, i.content, i.commentDate))
                }
            } else runOnUiThread {
                result.msg.show()
            }
        }

        // 配置适配器
        news_show_commentRv.apply {
            this.isNestedScrollingEnabled = true
            this.layoutManager = LinearLayoutManager(context)
            // 传入新闻ID
            this.adapter = NewsCommentAdapter(data, R.layout.fragment_news_comment)
            this.adapter?.notifyItemChanged(data.size)
        }
    }


    // 新闻评论模型
    private data class NewsCommentModel(
        val name: String,
        val content: String,
        val date: String
    )


    /**
     * 列表适配器
     */
    private class NewsCommentAdapter(
        val list: MutableList<NewsCommentModel>,
        val layoutID: Int
    ) : BaseRecyclerAdapter<NewsCommentModel>(list, layoutID) {
        override fun setData(
            view: BaseViewHolder.ViewFind,
            data: NewsCommentModel,
            position: Int,
            holder: BaseViewHolder
        ) {
            // 根据发布时间从大到小排序
            list.sortByDescending { it.date }

            // 设置动画
            holder.itemView.animation = App.getAnimationBottomAndTop()

            // 获取数据
            list[position].apply {
                // 填充数据
                // 自己设置头像
                holder.itemView.commentImage.setImageResource(R.mipmap.kkcomment)
                holder.itemView.commentName.text = this.name
                holder.itemView.commentContent.text = this.content
                holder.itemView.commentTime.text = this.date
            }
        }
    }


    /**
     * 发表新闻评论
     * @param id 新闻ID
     */
    private fun publishComment(id: Int) {
        news_comment_include.apply {
            // 监听文本点击事件
            // 获取内容
            val content = this.news_edit_ed.text.toString()
            // 判断不能为空
            if (content.isNotEmpty()) {
                // 开启协程
                coroutine(Dispatchers.Main) {
                    val result = api.postNewsComment(
                        getTokenStr,
                        JSONObject().apply {
                            // 组装数据
                            put("newsId", id)
                            put("content", content)
                        }.toString().toRequestBody(
                            "application/json".toMediaType()
                        )
                    )

                    // 判断是否发表成功
                    if (result.code == "200") {
                        // 清空原先数据
                        news_comment_include.news_edit_ed.setText("")
                        // 发表成功就调用列表适配器重新获取数据
                        rvAdapter()
                    } else runOnUiThread {
                        // 如果没有登录，侧跳转到登录界面
                        if (result.code == "401") {
                            startActivityUtils(this@ShowNewsActivity, LoginActivity())
                        }
                        result.msg.show()
                    }
                }

            } else runOnUiThread {
                "输入框不能为空!".show()
            }
        }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}